package com.zl.quickdoc.format;

import java.io.File;
import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerTemplater {

    public static final String ENCODING = "UTF-8";
    
    private static Configuration CFG = new Configuration(Configuration.VERSION_2_3_30);

    static {
        CFG.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_30));
        CFG.setEncoding(Locale.getDefault(), "UTF-8");
        CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CFG.setLocale(Locale.CHINA);
    }
    
    private String path;

    public void setPath(String path) {
        try {
            CFG.setDirectoryForTemplateLoading(new File(path).getParentFile());
        } catch (Exception e) {
        }
        this.path = path;
    }

    public FreemarkerTemplater(String dir) {
        try {
            if(!dir.startsWith("classpath:")) {
                CFG.setDirectoryForTemplateLoading(new File(dir).getParentFile());
            }else {
                dir = dir.replace("classpath:", "");
                CFG.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), new File(dir).getParent());
            }
        } catch (Exception e) {
        }
        this.path = dir;
    }

    
    /**
     * 生成 String
     */
    public String processString(Object params) {
        try {
            Template template = CFG.getTemplate(new File(this.path).getName(), ENCODING);
            StringWriter result = new StringWriter();
            template.process(params, result);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
